<template>
  <div class="notification-center">
    <!-- 通知图标 -->
    <el-popover
      :width="400"
      placement="bottom-end"
      trigger="click"
      popper-class="notification-popover"
      @show="handlePopoverShow"
    >
      <template #reference>
        <div class="notification-trigger" @click="handleTriggerClick">
          <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
            <el-icon
              :class="[
                'notification-icon',
                isHome ? 'notification-icon-dark' : 'notification-icon-light'
              ]"
            >
              <i-ep-bell />
            </el-icon>
          </el-badge>
          <div v-if="hasNewMessage" class="notification-indicator" />
        </div>
      </template>

      <!-- 通知内容 -->
      <div class="notification-content">
        <!-- 头部 -->
        <div class="notification-header">
          <h3 class="notification-title">消息通知</h3>
          <div class="notification-actions">
            <el-button
              type="primary"
              link
              size="small"
              :disabled="unreadCount === 0"
              @click="markAllAsRead"
            >
              全部已读
            </el-button>
            <el-button type="primary" link size="small" @click="clearAllMessages">清空</el-button>
          </div>
        </div>

        <!-- 分类标签 -->
        <div class="notification-tabs">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane name="ALL">
              <template #label>
                <el-badge :value="getTabCount(NOTIFICATION_TYPE.ALL)" :max="99" class="tab-badge">
                  <el-text>全部</el-text>
                </el-badge>
              </template>
            </el-tab-pane>
            <el-tab-pane name="SYSTEM">
              <template #label>
                <el-badge
                  :value="getTabCount(NOTIFICATION_TYPE.SYSTEM)"
                  :max="99"
                  class="tab-badge"
                >
                  <el-text>系统</el-text>
                </el-badge>
              </template>
            </el-tab-pane>
            <el-tab-pane name="COMMENT">
              <template #label>
                <el-badge
                  :value="getTabCount(NOTIFICATION_TYPE.COMMENT)"
                  :max="99"
                  class="tab-badge"
                >
                  <el-text>评论</el-text>
                </el-badge>
              </template>
            </el-tab-pane>
            <el-tab-pane name="LIKE">
              <template #label>
                <el-badge :value="getTabCount(NOTIFICATION_TYPE.LIKE)" :max="99" class="tab-badge">
                  <el-text>点赞</el-text>
                </el-badge>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 消息列表 -->
        <div class="notification-list">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>

          <div v-else-if="filteredMessages.length === 0" class="empty-container">
            <el-empty description="暂无消息" />
          </div>

          <div v-else class="message-list">
            <div
              v-for="message in filteredMessages"
              :key="message.id"
              class="message-item"
              :class="{ unread: !message.isRead }"
              @click="handleMessageClick(message)"
            >
              <div class="message-avatar">
                <el-avatar :size="40" :src="message.avatar || '/src/assets/image/avatar.png'" />
                <div class="message-type-icon" :class="getMessageTypeClass(message.type)">
                  <el-icon v-if="message.type === 'system'">
                    <i-ep-setting />
                  </el-icon>
                  <el-icon v-else-if="message.type === 'comment'">
                    <i-ep-chat-dot-round />
                  </el-icon>
                  <el-icon v-else-if="message.type === 'like'">
                    <i-ep-star />
                  </el-icon>
                </div>
              </div>

              <div class="message-content">
                <div class="message-header">
                  <span class="message-sender">{{ message.sender }}</span>
                  <span class="message-time">{{ getRelativeTime(message.createTime) }}</span>
                </div>
                <div class="message-text">
                  {{ message.content }}
                </div>
                <div v-if="message.link" class="message-link">
                  <el-button
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleMessageLink(message)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>

              <div class="message-actions">
                <el-button
                  v-if="!message.isRead"
                  type="primary"
                  link
                  size="small"
                  @click.stop="markAsRead(message.id)"
                >
                  标记已读
                </el-button>
                <el-button type="danger" link size="small" @click.stop="deleteMessage(message.id)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部 -->
        <div class="notification-footer">
          <el-button type="primary" link size="small" @click="viewAllMessages">
            查看全部消息
          </el-button>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {
  deleteNotification,
  clearAllNotifications,
  getNotificationList,
  getUnreadNotificationCount,
  markAllNotificationsAsRead,
  markNotificationAsRead
} from '@/api/notification';
import type { NotificationVO } from '@/api/notification/types';
import { useSocketStore } from '@/store/modules/socket';
// import { useUserStore } from '@/store/modules/user'; // 未使用，移除
import { getRelativeTime } from '@/utils/date';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { NOTIFICATION_TYPE } from '@/constants/common/notification-type';
import type { TabsPaneContext } from 'element-plus';

const route = useRoute();
const router = useRouter();
const isHome = computed(() => route.path === '/home');

// Emits
const emit = defineEmits(['message-click', 'message-link']);

// Store
const socketStore = useSocketStore();
// const userStore = useUserStore(); // 未使用，移除

// 响应式数据
const messages = ref<(NotificationVO & { id: string })[]>([]);
const unreadCount = ref(0);
const loading = ref(false);
const activeTab = ref('ALL');

// 拉取通知列表
const fetchNotifications = async () => {
  loading.value = true;
  try {
    const res = await getNotificationList({
      pageNum: 1,
      pageSize: 50
    });
    messages.value = (res.data.list || []).map((item: NotificationVO) => ({
      ...item,
      id: item.id
    }));
  } finally {
    loading.value = false;
  }
};

// 拉取未读数
const fetchUnreadCount = async () => {
  const res = await getUnreadNotificationCount();
  unreadCount.value = res.data || 0;
};

// 标记单条为已读
const markAsRead = async (messageId: string) => {
  console.log('markAsRead', messageId);
  await markNotificationAsRead(messageId);
  const msg = messages.value.find(m => m.id === messageId);
  if (msg) msg.isRead = true;
  fetchUnreadCount();
};

// 标记全部为已读
const markAllAsRead = async () => {
  await markAllNotificationsAsRead();
  messages.value.forEach(m => (m.isRead = true));
  fetchUnreadCount();
  ElMessage.success('已标记所有消息为已读');
};

// 删除单条
const deleteMessage = async (messageId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteNotification(messageId);
    const idx = messages.value.findIndex(m => m.id === messageId);
    if (idx > -1) messages.value.splice(idx, 1);
    fetchUnreadCount();
    ElMessage.success('消息已删除');
  } catch {}
};

// 清空所有消息
const clearAllMessages = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有消息吗？此操作不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await clearAllNotifications();
    messages.value = [];
    fetchUnreadCount();
    ElMessage.success('所有消息已清空');
  } catch {}
};

// 计算属性
const filteredMessages = computed(() => {
  if (activeTab.value === NOTIFICATION_TYPE.ALL) {
    return messages.value;
  }
  return messages.value.filter(msg => msg.type === activeTab.value);
});

// 获取标签页消息数量
const getTabCount = (tab: string) => {
  if (tab === NOTIFICATION_TYPE.ALL) {
    return messages.value.filter(msg => !msg.isRead).length;
  }
  return messages.value.filter(msg => msg.type === tab && !msg.isRead).length;
};

// 判断是否有消息
// const hasMessage = (tab: NOTIFICATION_TYPE) => getTabCount(tab) > 0; // 未使用，移除

// 获取消息类型样式类
const getMessageTypeClass = (type: string) => {
  const classMap: Record<string, string> = {
    SYSTEM: 'type-system',
    COMMENT: 'type-comment',
    LIKE: 'type-like'
  };
  return classMap[type] || 'type-default';
};

const hasNewMessage = ref(false);
let lastUnreadCount = 0;

watch(unreadCount, newVal => {
  if (newVal > lastUnreadCount) {
    hasNewMessage.value = true;
  }
  lastUnreadCount = newVal;
});

// 处理弹窗显示
const handlePopoverShow = () => {
  // 弹窗显示时停止闪烁动画
  hasNewMessage.value = false; // This line is removed as per the new logic
};

// 处理触发器点击
const handleTriggerClick = () => {
  activeTab.value = NOTIFICATION_TYPE.ALL;
  // 可以在这里添加点击逻辑
};

// 处理标签页切换
const handleTabClick = (tab: TabsPaneContext) => {
  activeTab.value = String(tab.paneName);
};

// 处理消息点击
const handleMessageClick = (message: NotificationVO) => {
  if (!message.isRead) {
    markAsRead(message.id);
  }
  emit('message-click', message);
};

// 处理消息链接点击
const handleMessageLink = (message: NotificationVO) => {
  emit('message-link', message);
  if (message.link) {
    window.open(message.link, '_blank');
  }
};

// 查看全部消息
const viewAllMessages = () => {
  router.push('/notice/index');
};

// 生命周期
onMounted(() => {
  fetchNotifications();
  fetchUnreadCount();

  // 监听刷新标记
  watch(
    () => socketStore.notificationRefreshFlag,
    () => {
      fetchNotifications();
      fetchUnreadCount();
    }
  );

  // 监听WebSocket连接状态
  watch(
    () => socketStore.isConnectWebSocket,
    isConnected => {
      if (isConnected) {
        console.log('WebSocket已连接，开始监听消息');
      }
    }
  );

  // 请求浏览器通知权限
  if (Notification.permission === 'default') {
    Notification.requestPermission();
  }
});

onUnmounted(() => {
  // 清理事件监听器
  // window.removeEventListener('newNotification', (window as any)._handleNewNotification); // 未使用，移除
  // delete (window as any)._handleNewNotification; // 未使用，移除
});

// 暴露方法给父组件
defineExpose({
  markAsRead,
  markAllAsRead,
  clearAllMessages
});
</script>

<style lang="scss" scoped>
.notification-center {
  display: inline-block;
}

.notification-trigger {
  position: relative;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
  }
}

.notification-badge {
  display: flex;
  align-items: center;
}

.notification-icon {
  font-size: 22px;
  transition: color 0.3s;
}
.notification-icon-light {
  color: #2c3e50;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.notification-icon-dark {
  color: #fffbe6;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.32);
}

.notification-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.notification-content {
  max-height: 500px;
  overflow: hidden;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px 0;
  border-bottom: 1px solid var(--el-border-color-light);
  margin-bottom: 16px;
}

.notification-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.notification-actions {
  display: flex;
  gap: 8px;
}

.notification-tabs {
  padding: 0 16px;
  margin-bottom: 16px;
}

.tab-badge {
  margin-left: 4px;
}

.notification-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 0 16px;
}

.loading-container,
.empty-container {
  padding: 20px;
  text-align: center;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background-color: var(--el-fill-color-light);
    border-color: var(--el-color-primary);
  }

  &.unread {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-7);
  }
}

.message-avatar {
  position: relative;
  flex-shrink: 0;
}

.message-type-icon {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: white;

  &.type-system {
    background-color: var(--el-color-info);
  }

  &.type-comment {
    background-color: var(--el-color-success);
  }

  &.type-like {
    background-color: var(--el-color-warning);
  }
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.message-sender {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.message-text {
  color: var(--el-text-color-regular);
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 4px;
  word-break: break-word;
}

.message-link {
  margin-top: 4px;
}

.message-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex-shrink: 0;
}

.notification-footer {
  padding: 12px 16px;
  border-top: 1px solid var(--el-border-color-light);
  text-align: center;
  margin-top: 16px;
}

// 深色模式适配
:deep(.el-popover.notification-popover) {
  .message-item {
    background-color: var(--el-bg-color);

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    &.unread {
      background-color: var(--el-color-primary-light-9);
    }
  }
}
</style>
